﻿/**
 * 保留版权 : CopyRright (c) 2015  于继业 版权所有
 * 文件名称 : WDTUtil.cs:
 * 文件编号 : 
 * 功能描述 : 网店通的工具类
 * 文件版本 : 2015071501
 * 创建人名 : 于继业
 * 创建日期 : 2015/7/15
 * 修改人名 :
 * 修改日期 :
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace IF.Utils
{
    public class WDTUtil
    {
        //静态常量
        public const String SID = "ruguo2";//卖家账号id
        public const String APPKEY = "ruguo_os";//由旺店通分配的第三方应用帐号
        public const String APPSECRET = "375f17b4b20c7795566e98484133c1c0";//应用秘钥
        public const String SHOPNO = "020"; //商店编号
        public const String KEY_FLAG = "KEY";
        public const String VALUE_FLAG = "VALUE";
        public const String WDT_REQUEST_URL = "http://api.wangdian.cn";

        ////****************测试**************************************************
        //public const String SID = "wdt2_opentest";//卖家账号id
        //public const String APPKEY = "ruguo2test";//由旺店通分配的第三方应用帐号
        //public const String APPSECRET = "12345";//应用秘钥
        //public const String SHOPNO = "shop_test"; //商店编号
        //public const String KEY_FLAG = "KEY";
        //public const String VALUE_FLAG = "VALUE";
        //public const String WDT_REQUEST_URL = "http://121.199.38.85";
        ////****************测试**************************************************
        /// <summary>
        /// <para>
        /// 1、获得数字签名
        /// </para>
        /// </summary>
        /// <param name="dicReq">请求的参数</param>
        /// <returns>数字签名</returns>
        public static string getSign(Dictionary<string, string> dicReq)
        {
            return MD5Encrypt(CreateParam(dicReq));
        }

        /// <summary>
        /// <para>
        /// 1、加密请求的字符串
        /// </para>
        /// </summary>
        /// <param name="strText">要加密的请求字符串</param>
        /// <returns>加密以后的字符串</returns>
        public static string MD5Encrypt(string strText)
        {
            MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strText));
            string strMd5 = BitConverter.ToString(result);
            strMd5 = strMd5.Replace("-", "");
            return strMd5.ToLower();// System.Text.Encoding.Default.GetString(result);
        }

        /// <summary>
        /// <para>
        /// 1、格式化map中的数据，得字符串为 "04-key1:0006-value1;04-key2:0006-value2"
        /// </para>
        /// </summary>
        /// <param name="dicReq">请求的参数字典</param>
        /// <param name="isLower">是否转换成小写</param>
        /// <returns>将参数转换成字符串</returns>
        public static string CreateParam(Dictionary<string, string> dicReq, bool isLower = false)
        {
            //排序
            dicReq = dicReq.OrderBy(r => r.Key).ToDictionary(r => r.Key, r => r.Value);

            StringBuilder sb = new StringBuilder();
            int i = 0;
            foreach (var item in dicReq)
            {
                if (item.Key == "sign")
                {
                    continue;
                }
                if (i > 0)
                {
                    sb.Append(";");
                }
                i++;
                sb.Append(item.Key.Length.ToString("00"));
                sb.Append("-");
                sb.Append(item.Key);
                sb.Append(":");

                sb.Append(item.Value.Length.ToString("0000"));
                sb.Append("-");
                sb.Append(item.Value);
            }
            if (isLower)
            {
                dicReq.Add("sign", MD5Encrypt(sb + APPSECRET).ToLower());
            }
            else
            {
                dicReq.Add("sign", MD5Encrypt(sb + APPSECRET));
            }
            sb = new StringBuilder();
            i = 0;
            foreach (var item in dicReq)
            {
                if (i == 0)
                    sb.Append(string.Format("{0}={1}", item.Key, HttpUtility.UrlEncode(item.Value, Encoding.UTF8)));
                else
                    sb.Append(string.Format("&{0}={1}", item.Key, HttpUtility.UrlEncode(item.Value, Encoding.UTF8)));
                i++;
            }

            return sb.ToString();
        }

        /// <summary>
        /// <para>
        /// 1、旺店通post提交
        /// </para>
        /// </summary>
        /// <param name="url">请求方法</param>
        /// <param name="postData">传递参数</param>
        /// <returns>返回的结果</returns>
        public static string SendPost(string url, Dictionary<string, string> dicReq)
        {
            //CreateParam(dic, true);
            //获得数字签名
            string postData = CreateParam(dicReq);

            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream serviceRequestBodyStream = null;
            string result = string.Empty;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(WDT_REQUEST_URL + url);
                request.Credentials = CredentialCache.DefaultCredentials;
                request.KeepAlive = false;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                UTF8Encoding encoding = new UTF8Encoding();
                byte[] bodyBytes = encoding.GetBytes(postData);
                request.ContentLength = bodyBytes.Length;
                using (serviceRequestBodyStream = request.GetRequestStream())
                {
                    serviceRequestBodyStream.Write(bodyBytes, 0, bodyBytes.Length);
                    serviceRequestBodyStream.Close();
                    using (response = (HttpWebResponse)request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            result = reader.ReadToEnd();
                            reader.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }

            return result;
        }

        // 时间戳转为C#格式时间
        public static DateTime StampToDateTime(string timeStamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);

            return dateTimeStart.Add(toNow);
        }

        // DateTime时间格式转换为Unix时间戳格式
        public static int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
    }
}
